<?php include '_init_.php';?>
<?php include 'page_header.php';?>
<?php
$dtCatalog = new DataTable(constant('DB_TABLE_CATALOG'));
$json = new Services_JSON();
$id = isset($_REQUEST['id'])?intval($_REQUEST['id']):0;
	if($id < 1)
		exit("Please specify ID");
	$orderManager = Order_Manager::getOrderManager($_REQUEST['id']);
	if(!$orderManager)
		exit('Data not exist anymore');
	if($orderManager->getStatus() != Order_Manager::$STATUS_CREATING)
	{
			exit("Order doesn't editable");
	}
	$orderManager->setEditing();
	$act = isset($_REQUEST['act'])?$_REQUEST['act']:'';
	if($act == 'save')
	{
		$updateOrderData = $_REQUEST;
		
		
		//zoom size list
		
		$r_size_table = $json->decode(Util::work_str($updateOrderData['_size_table'],2));
		$r_size_frame_table = $json->decode(Util::work_str($updateOrderData['_size_frame_table'],2));
		$r_gift_table = $json->decode(Util::work_str($updateOrderData['_gift_table'],2));
		$updateOrderData['zoom_list'] = array();
		$updateOrderData['zoom_frame_list'] = array();
		foreach($r_size_table as $tmpData)
	{
		$updateOrderData['zoom_list'][] = array('size_id'=>$tmpData->size_id,'size_name'=>$tmpData->size_name,'number'=>$tmpData->number,'is_gift'=>$tmpData->is_gift);
		
		//size frame info
		$size_frame_list = $r_size_frame_table[$tmpData->size_id];
		foreach($size_frame_list as $tmpData2)
		{
			$updateOrderData['zoom_frame_list'][] = array('size_id'=>$tmpData->size_id,'frame_id'=>$tmpData2->frame_id,'frame_name'=>$tmpData2->frame_name,'is_gift'=>$tmpData2->is_gift);
		}
	}
	//gift list
	$updateOrderData['gift_list'] = array();
	foreach($r_gift_table as $tmpData)
	{
		$updateOrderData['gift_list'][] = array('gift_id'=>$tmpData->gift_id,'gift_name'=>$tmpData->gift_name,'number'=>$tmpData->number,'is_gift'=>$tmpData->is_gift);
	}
	
		$orderManager->setInfo($updateOrderData);
		
		
		$orderEstimatorHelper = new Order_Estimator($orderManager);
		$priceTable = $orderEstimatorHelper->estimate();
		$orderManager->setEstimatePrice($priceTable);	
		$orderManager->persistOrderInfo();
		if($_REQUEST['is_ajax_submit_form'])
		{
			ob_clean();
			echo 'ok:'.$priceTable['total'];
			exit();
		}
		$orderManager->setNotEditing();
		header('Location:add-cosd.php?id='.$orderManager->getId());
		exit();
	}
	
	if($act == 'setcatalog')
	{
		$catalogName = $_REQUEST['catalogname'];
		$orderManager->setCatalog($catalogName);
		$orderEstimatorHelper = new Order_Estimator($orderManager);
		$priceTable = $orderEstimatorHelper->estimate();
		$orderManager->setEstimatePrice($priceTable);	
		$orderManager->persistOrderInfo();
	}


$orderManager->init();
$pageInfo = $orderManager->getInfo();
if(is_array($pageInfo['zoom_list']) && count($pageInfo['zoom_list']) > 0 && !is_string($pageInfo['zoom_list'][0]))
{
	$pageInfo['json_photo_size'] = $json->encode($pageInfo['zoom_list']);
}else{
	$pageInfo['json_photo_size'] = '[]';
}

if(is_array($pageInfo['zoom_frame_list']) && count($pageInfo['zoom_frame_list']) > 0 && !is_string($pageInfo['zoom_frame_list'][0]))
{
	$tmpFrameList = $pageInfo['zoom_frame_list'];
	$tmpFrameMap = new stdClass();
	foreach($tmpFrameList as $tmpData)
	{
		$tmpSizeId = $tmpData['size_id'];
		$ref_size_frame_obj = &$tmpFrameMap->$tmpSizeId;
		$tmpSizeFrameObj = new stdClass();
		$tmpSizeFrameObj->frame_id = $tmpData['frame_id'];
		$tmpSizeFrameObj->frame_name = $tmpData['frame_name'];
		$ref_size_frame_obj[] = $tmpSizeFrameObj;
	}
	$pageInfo['json_photo_size_frame'] = $json->encode($tmpFrameMap);
}else{
	$pageInfo['json_photo_size_frame'] = '{}';
}
if(is_array($pageInfo['gift_list']) && count($pageInfo['gift_list']) > 0 && !is_string($pageInfo['gift_list'][0]))
{
	$pageInfo['json_gift'] = $json->encode($pageInfo['gift_list']);
}else{
	$pageInfo['json_gift'] = '[]';
}

	
$catlog_list = $dtCatalog->get_list('','name');
$dtBenzuStyle = new DataTable(constant('DB_TABLE_BENZU_STYLE'));
$benzustyle_list = $dtBenzuStyle->get_list();
?>
<script language="javascript" src="js/add_cosc_php_page.js"></script>
<script language="javascript" src="js/jquery.form.js"></script>
<script language="javascript">

function edit_tob(size_id,frame_index,frame_id,size_name,isgift) {
		rAlert("backstage-editib.php?addcostcall=1&size_id="+size_id+"&frame_index="+frame_index+"&frame_id="+frame_id+'&size_name='+size_name + '&isgift='+isgift , null, "像框管理", 625, 200);
}

$(global_doestimater_dispatcher).trigger('estimate_ajax_back');
function edit_tol(id) {
	do_estimate();
	$(global_doestimater_dispatcher).bind('estimate_ajax_back',edit_tol_core);
		
}
function edit_tol_core()
{
	$(global_doestimater_dispatcher).unbind('estimate_ajax_back',edit_tol_core);
	rAlert("cosil.php?id=<?php echo $orderManager->getId();?>" , null, "消費明細", 704,704 );
}
$(function(){
//set info value to ui
$('select[name=type]').val('<?php echo $pageInfo['type'];?>');
var benzuStyleList = '<?php echo $pageInfo['benzu_style'];?>';
$.each(benzuStyleList.split(","),function(k,v){
	$('input[type=checkbox][value='+v+'].jq_benzustyle').attr('checked',true);
});

$('input[name=catalog][type=radio][value=<?php echo $pageInfo['catalog'];?>]').attr('checked',true);
//add change catalog handler
$('input[name=catalog][type=radio]').bind('change',function(){
	var catalogName = $(this).val();
	document.location = '?act=setcatalog&id=<?php echo $orderManager->getId();?>&catalogname='+catalogName;
});
});
</script>
<div id="main"><!-- start #main //-->
<form method="post" action='add-cosc.php' id="form_main">
<input type="hidden" name="act" value="save"/>
<input type="hidden" name="id" value="<?php echo $orderManager->getId();?>"/>
<input type="hidden" name="_size_table" value=""/>
<input type="hidden" name="_size_frame_table" value=""/>
<input type="hidden" name="_gift_table" value=""/>
<input type="hidden" name="is_ajax_submit_form" value=""/>
<div id="tita">
  <div class="tita-1">
    <h3>預約項目</h3>
    <img src="images/point-1.gif" width="18" height="18" /> 
    <h4>拍攝相關</h4>
    <img src="images/point-1.gif" width="18" height="18" /> 
    <h4>贈品選項</h4>
    </div>
  <div class="tita-2">預約單號 No.<?php echo Util::html_safe($pageInfo['number']);?></div>
  </div>
  <div id="mainf" class="clearfix"><!-- start #mainf //-->
  <div class="mainf-2 jq_catalog_selector">
    <ul>      
      <?php foreach($catlog_list as $tmpData):?>
      <li class="mainf-1d"><input name="catalog" type="radio" class="mainf-radiobtn"  value="<?php echo $tmpData['name'];?>" /><?php echo $tmpData['name'];?></li>
      <?php endforeach;?>
    </ul>
    </div>
    
    <div class="mainf-3">
    <ul>
     <li class="mainf-1e">預約類別
       <label for="select2"></label>
       <select name="type" class="maine-keyinm" >
         <option value="寶寶照">寶寶照</option>
         <option value="全家福">全家福</option>
         <option value="個人照">個人照</option>
       </select>
     </li>
      <li class="mainf-1e">數位光碟<input name="disk_number" type="text"  class="maine-keying _validate_form_int" value="<?php echo Util::html_safe($pageInfo['disk_number']);?>"/>
      組
      </li>
      <li class="mainf-1e2">增加數位光碟<input name="disk_number_add" type="text"  class="maine-keying _validate_form_int" value="<?php echo Util::html_safe($pageInfo['disk_number_add']);?>"/>
      組
      </li>
      <li class="mainf-1e">相本數量<input name="benzu_number" type="text"  class="maine-keying _validate_form_int" value="<?php echo Util::html_safe($pageInfo['benzu_number']);?>"/></li>
      <li class="mainf-1f jq_benzustyle_selector">相本樣式</li>
    
      	<?php foreach($benzustyle_list as $tmpData):?>
      		  <li class="mainf-1c"> <input type="checkbox" name="benzu_style[]" class="jq_benzustyle" value="<?php echo $tmpData['name'];?>"/>&nbsp;<?php echo $tmpData['name'];?></li>
      	<?php endforeach;?>
      	
      	<li class="mainf-1e">修改像本增加差價<input name="benzu_customize_price" type="text"  class="maine-keying _validate_form_float" value="<?php echo $pageInfo['benzu_customize_price'];?>"/>&nbsp;元</li>
      </ul>
     </div>
    <div class="mainf-3">
    <ul>
     <li class="mainf-1e" style="width:300px">拍攝人數（成人）
     <input name="person_number" type="text"  class="maine-keying _validate_form_int" value="<?php echo Util::html_safe($pageInfo['person_number']);?>"/>
       <label for="select"></label>
     </li>
      <li class="mainf-1e" style="width:300px">服裝造型（成人）
      <input name="dress_number" type="text"  class="maine-keying _validate_form_int" value="<?php echo Util::html_safe($pageInfo['dress_number']);?>"/>
      <label for="select"></label>
      </li>
       <li class="mainf-1e" style="width:300px">拍攝人數（小孩）
     <input name="person_number2" type="text"  class="maine-keying _validate_form_int" value="<?php echo Util::html_safe($pageInfo['person_number2']);?>"/>
       <label for="select"></label>
     </li>
      <li class="mainf-1e" style="width:300px">服裝造型（小孩）
      <input name="dress_number2" type="text"  class="maine-keying _validate_form_int" value="<?php echo Util::html_safe($pageInfo['dress_number2']);?>"/>
      <label for="select"></label>
      </li>
      
       <li class="mainf-1e2" style="width:300px">*增加拍攝人數（成人）
     <input name="person_number_add" type="text"  class="maine-keying _validate_form_int" value="<?php echo Util::html_safe($pageInfo['person_number_add']);?>"/>
       <label for="select"></label>
       </li>
     <li class="mainf-1e2" style="width:300px">*增加服裝造型（成人）
      <input name="dress_number_add" type="text"  class="maine-keying _validate_form_int" value="<?php echo Util::html_safe($pageInfo['dress_number_add']);?>"/>
      <label for="select"></label>
      
      <li class="mainf-1e2" style="width:300px">*增加拍攝人數（小孩）
     <input name="person_number2_add" type="text"  class="maine-keying _validate_form_int" value="<?php echo Util::html_safe($pageInfo['person_number2_add']);?>"/>
       <label for="select"></label>
       </li>
     <li class="mainf-1e2" style="width:300px">*增加服裝造型（小孩）
      <input name="dress_number2_add" type="text"  class="maine-keying _validate_form_int" value="<?php echo Util::html_safe($pageInfo['dress_number2_add']);?>"/>
      <label for="select"></label>
     </li>
      </ul>
     </div>
     
  <script language="javascript">
     var global_size_table = <?php echo $pageInfo['json_photo_size'];?>;
     var global_size_frame_table = <?php echo $pageInfo['json_photo_size_frame'];?>;
     function dialog_function_get_size_info()
     {
     	return global_size_table;
     }
     function dialog_function_add_size_callback(sizeInfo)
     {
     	rClose();
     	$.each(sizeInfo,function(i,v){
     		global_size_table.push(v);
     	});
     	refreshSizeHtml();
     	do_estimate();
     }
     function dialog_function_set_size_callback(sizeInfo)
     {
     	rClose();
     	var itemData = sizeInfo[0];
     	$.each(global_size_table,function(i,v){
     		if(v.size_id == itemData.size_id)
     		{
     			global_size_table[i]['number'] = itemData.number;
     			global_size_table[i]['is_gift'] = itemData.is_gift;
     			return false;
     		}
     	});
     	refreshSizeHtml();
     	do_estimate();
     }

     $(function(){
     	refreshSizeHtml();
     	refreshGiftHtml();
     });
     function refreshSizeHtml()
     {
     	//delete li except the last one
     	var liLen = $('#html_sizecontainer li').length - 1 ;
     	$('#html_sizecontainer li').each(function(i,v){
     		if(i < liLen)
     		{
     			$(v).remove();
     		}
     	});
     	$.each(global_size_table,function(k,v){
     		var newItem = $('<li class="maina-1a"><input type="checkbox" class="jq_select_class_sizelist" value="'+v.size_id+'"/>&nbsp;放大<img width="8" height="8" src="images/line3.gif">'+v.size_name+' 吋 X '+v.number+'</li>');
     		if(v.is_gift == 'Y')
     		{
     			newItem.append('<span>(贈品)</span>');
     		}
     		if($('#html_sizecontainer li').length > 1)
     		{
     			newItem.insertAfter($('#html_sizecontainer li:first'));
     		}else{
     			 newItem.insertBefore($('#html_sizecontainer li:last'));
     		}
     	});
     	//refresh size frame selector
     	//create a new list then copy necessary data to the new array, end assign the new array to data and refresh ui
     	var tmp_table = [];
     	$.each(global_size_table,function(k,v){
     		if(tmp_table[v.size_id] == undefined)
     		{
     			tmp_table[v.size_id] = new Array();
     		}
     		var oldDataSize = 0;
     		if(global_size_frame_table[v.size_id])
     		{
     			oldDataSize = global_size_frame_table[v.size_id].length;
     		}
     		for(i= 0; i < v.number; i++)
     		{
     			if(i < oldDataSize)
     			{
     				tmp_table[v.size_id][i] = global_size_frame_table[v.size_id][i];
     			}else{
     				tmp_table[v.size_id][i] = false;
     			}
     		}
     	});
     	global_size_frame_table = tmp_table;
     	refresh_size_frame_ui();
  
     }
     function refresh_size_frame_ui()
     {
     	//refresh ui
     	$('#html_sizeframe_container li').remove();
     	for(si = 0; si < global_size_table.length;si++)
     	{
     	for(var k in global_size_frame_table)
     	{
     		if(k != global_size_table[si].size_id)
     		{
     			continue;
     		}
     		v = global_size_frame_table[k];
     			$.each(v,function(k2,v2){
     				//get size name
     				var size_name = '';
     				$.each(global_size_table,function(k3,v3){
     					if(v3.size_id == k)
     					{
     						size_name = v3.size_name
     						return;
     					}
     				});
     			  if(v2 && v2.frame_id.length > 0)
     			  {
     			  	  var newItem = $('<li class="maina-1j"><input type="checkbox" name=""/>&nbsp;'+size_name+' 像框<img src="images/line3.gif" width="21" height="12" />'+v2.frame_name+'<img src="images/line3.gif" width="21" height="12" /><a href="#" onclick="edit_tob('+k+','+k2+','+v2.frame_id+',\''+size_name+'\',\''+v2.is_gift+'\'); return false;">選擇</a></li></li>');
     			  	 if(v2.is_gift == 'Y')
     				{
     						newItem.append('<span>(贈品)</span>');
     					}
     			  	 $('#html_sizeframe_container').append(newItem);
     			  	
     			  }else{
     			  	
     			  	  var newItem = $('<li class="maina-1j"><input type="checkbox" name=""/>&nbsp;'+size_name+' 像框<img src="images/line3.gif" width="21" height="12" /><a href="#" onclick="edit_tob('+k+','+k2+',\'\',\''+size_name+'\',\''+v2.is_gift+'\'); return false;">選擇</a></li>');
     			  	  if(v2.is_gift == 'Y')
     				{
     						newItem.append('<span>(贈品)</span>');
     					}
     			  	 $('#html_sizeframe_container').append(newItem);
     			  	
     			  }
      		});
      		
      		break;
     	}
     	}
     }
     function dialog_function_set_size_frame_callback(size_id,frame_index,frame_id,frame_name,is_gift)
     {
     	rClose();
     	global_size_frame_table[size_id][frame_index] = {'frame_id':frame_id,'frame_name':frame_name,'is_gift':is_gift};
     	refresh_size_frame_ui();
     	do_estimate();
     }
     function dialog_function_set_gift_get_isgift()
     {
     	return $('input[name=gift_list_isgift]').val();
     }
     function dialog_function_set_gift_isgift_callback(isgift)
     {
     	$('input[name=gift_list_isgift]').val(isgift);
     }
     </script>
     <div class="mainf-3">
    <ul id="html_sizecontainer">
          <li class="maina-1d">
        <a href="#" onclick="javascript:edit_toa_add(1118);return false;"><img src="images/edit-btn-3.png" height="24" width="24"></a>
        <a href="#" onclick="javascript:edit_toa(1118);return false;"><img src="images/edit-btn-4.png" height="24" width="24"></a>
        <a href="#" onclick="javascript:deleteZoomlist();return false;"><img src="images/edit-btn-5.png" height="24" width="24"></a>
         </li>
      </ul>
     </div>
     <script language="javascript">
     	function edit_toa_add() {
     		var idlist = '';
     		$.each(global_size_table,function(k,v){
     		idlist = v.size_id + ',';

     		});
			rAlert("backstage-editia-add.php?addcostcall=1&idlist="+idlist , null, "相片尺寸列表", 600, 400);
		}

    	 function edit_toa() {
    	 	if($('.jq_select_class_sizelist:checked').length != 1)
      		{
      			alert('請選擇一個放大尺寸');
      			return;
      		}
      		var sizeid = $('.jq_select_class_sizelist:checked').val();
      		rAlert("backstage-editia.php?addcostcall=1&sizeid="+sizeid , null, "相片尺寸列表", 600, 400);
		}
		function deleteZoomlist()
		{
			if($('.jq_select_class_sizelist:checked').length == 0)
      		{
      			alert('請選擇放大尺寸');
      			return;
      		}
      		$('.jq_select_class_sizelist:checked').each(function(i,v){
      			var sizeid = $(v).val();
      			$.each(global_size_table,function(i2,v2){
      				if(sizeid == v2.size_id)
      				{
      					global_size_table.splice(i2,1);
      					return false;
      				}
      			});
      		});
      		refreshSizeHtml();
      		do_estimate();
		}
     </script>
     <div class="mainf-3">
    <ul id="html_sizeframe_container">

      </ul>
     </div>
     <script language="javascript">
 var global_gift_table = <?php echo $pageInfo['json_gift'];?>;
function dialog_function_get_gift_info()
{
    return global_gift_table;
}


     
function dialog_function_add_gift_callback(giftInfo)
{
	rClose();
     	$.each(giftInfo,function(i,v){
     		global_gift_table.push(v);
     	});
     	refreshGiftHtml();
     	do_estimate();
}
function dialog_function_set_gift_callback(giftInfo)
{
     	rClose();
     		var itemData = giftInfo[0];
     	$.each(global_gift_table,function(i,v){
     		if(v.gift_id == itemData.gift_id)
     		{
     			global_gift_table[i]['number'] = itemData.number;
     			global_gift_table[i]['is_gift'] = itemData.is_gift;
     			return false;
     		}
     	});
     	refreshGiftHtml();
     	do_estimate();
}
function refreshGiftHtml()
{
	//delete li except the last one
     	var liLen = $('#html_gift_container li').length - 1 ;
     	$('#html_gift_container li').each(function(i,v){
     		if(i < liLen)
     		{
     			$(v).remove();
     		}
     	});
     	$.each(global_gift_table,function(k,v){
     		var newItem = $('<li class="maina-1a"><input type="checkbox" class="jq_select_class_giftlist" value="'+v.gift_id+'"/>&nbsp;'+v.gift_name+'<img src="images/line3.gif" width="21" height="12" />'+v.number+'</li>');
     		 if(v.is_gift == 'Y')
     				{
     						newItem.append('<span>(贈品)</span>');
     					}
     		if($('#html_gift_container li').length > 1)
     		{
     			newItem.insertAfter($('#html_gift_container li:first'));
     		}else{
     			 newItem.insertBefore($('#html_gift_container li:last'));
     		}
     	});
}
</script>
<div class="mainf-3">
    <ul id="html_gift_container">
     
       
          <li class="maina-1d">
        <a href="#" onclick="javascript:edit_toc_add();return false;"><img src="images/edit-btn-3.png" height="24" width="24"></a>
        <a href="#" onclick="javascript:edit_toc();return false;"><img src="images/edit-btn-4.png" height="24" width="24"></a>
        <a href="#" onclick="javascript:deleteGiftlist();return false;"><img src="images/edit-btn-5.png" height="24" width="24"></a>
          </li>
      </ul>
     </div>
     <script language="javascript">
      function edit_toc_add() {
     	 var idlist = '';
     		$.each(global_gift_table,function(k,v){
     		idlist = v.gift_id + ',';

     		});
      	rAlert("backstage-editic-add.php?addcostcall=1&idlist="+idlist , null, "贈品管理", 625, 260);
      }
      
    	 function edit_toc() {
    	 	if($('.jq_select_class_giftlist:checked').length != 1)
      		{
      			alert('請選擇一個贈品');
      			return;
      		}
      		var giftid = $('.jq_select_class_giftlist:checked').val();

      		rAlert("backstage-editic.php?addcostcall=1&giftid="+giftid , null, "贈品管理", 625, 400);
		}
		function deleteGiftlist()
		{
			if($('.jq_select_class_giftlist:checked').length == 0)
      		{
      			alert('請選擇贈品');
      			return;
      		}
      		$('.jq_select_class_giftlist:checked').each(function(i,v){
      			var giftid = $(v).val();
      			$.each(global_gift_table,function(i2,v2){
      				if(giftid == v2.gift_id)
      				{
      					global_gift_table.splice(i2,1);
      					return false;
      				}
      			});
      		});
      		refreshGiftHtml();
      		do_estimate();
		}

     </script>
     
</div><!-- end #maine //-->
     <div class="mainf-3">
    <ul>
      <li class="mainf-1k">消費總金額<img src="images/line3.gif" width="21" height="12" /><span id='lable_total_price'><?php echo $pageInfo['price']['total'];?></span></li>
          <li class="maina-1d"><a href="#" onclick="javascript:edit_tol();return false;"><img src="images/edit-shop.gif" width="64" height="17" /></a></li>
      </ul>
     </div>
     
       	<script language="javascript">
    function checkForm()
    {
    	var valid = true;
    	$('.form_value_error').removeClass('form_value_error');
    	//check catalog
    	if($('input[name=catalog][checked]').length < 1)
    	{
    		$('.jq_catalog_selector').addClass('form_value_error');
    		valid = false;
    	}
    	//check benzu style
    	if($('input[type=checkbox][checked].jq_benzustyle').length < 1)
    	{
    		$('.jq_benzustyle_selector').addClass('form_value_error');
    	}
    	return valid;
    }
  	function saveForm()
  	{
  		if(!checkForm())
  			return false;
  		$('input[name=_size_table]').val($.toJSON(global_size_table));
  		$('input[name=_size_frame_table]').val($.toJSON(global_size_frame_table));
  		$('input[name=_gift_table]').val($.toJSON(global_gift_table));
  		$('input[name=is_ajax_submit_form]').val('');
  		document.forms[0].submit();
  		return false;
  	}
  	</script>
    <div id="paged"><!-- start #pagec //-->
    <a href="add-cosb.php?id=<?php echo $orderManager->getId();?>"><img src="images/pagec2-prev.gif" width="77" height="29" /></a><a href="#" onclick="return saveForm();"><img src="images/pagec2-next.gif" width="77" height="29" /></a>
  </div><!-- end #paged //-->
    </div><!-- start #mainf //-->
</div><!-- end #tita //-->
</form>
</div><!-- end #main //-->
<?php include 'page_footer.php';?>